<?php
namespace app\article\service;

use app\common\library\Service;
use think\Db;

class Comment extends Service
{

    // 模型验证
    protected $modelValidate = null;
    // 批量验证
    protected $batchValidate = null;

    protected function _initialize() {
        parent::_initialize();
        $this->model = model('article/Comment');
    }

    /**
     * 评论列表
     * @param mixed $maps   查询条件
     * @return mixed
     */
    public function lists($maps = '', $order = '', $page = 0, $limit = 12, $field = true, $relations = []) {
        $result = $this->model->order($order)->field($field);
        if (isset($maps['article_id'])) {
            $result = $result->where('article_id','=',$maps['article_id']);
        }
        if (isset($maps['keywords'])) {
            $result = $result->where('username|content','like','%'.$maps['keywords'].'%');
        }
        if (isset($maps['status'])) {
            $result = $result->where('status','=',$maps['status']);
        }
        if (isset($maps['current_id'])) {
            $result = $result->where('current_id','=',$maps['current_id']);
        }
        if (isset($maps['site_id'])) {
            $result = $result->where('site_id','=',$maps['site_id']);
        }
        if (isset($maps['pid'])) {
            $result = $result->where('pid','=',$maps['pid']);
        }

        if($page !== false) {
            $result = $result->paginate($limit, '', ['page' => $page]);
        } else {
            $result = $result->limit($limit)->select();
        }
        if (isset($maps['type']) && $maps['type'] == 'sum') {
            $result = $result->count();
        }

        /* 关联数据获取 */
        if(!empty($relations)) {
            foreach ($result as $key => $value) {
                array_map(function($e) use (&$value) {
                    $e = trim($e);
                    $value->$e = $value->$e ?: new \stdClass(); // 注意没有数据不要返回默认的 NULL
                }, $relations);
            }
        }

        return $result;
    }

    /**
     * 添加
     * @method create
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    public function create($data = [])
    {
        if ($data['pid'] > 0) {
            $comment_info = model('article/Comment')
                            ->where('id','=',$data['pid'])
                            ->where('current_id','=',$data['current_id'])
                            ->where('status','=',1)
                            ->find();
            if (!$comment_info) {
                $this->error = '父级评论信息未找到';
                return false;
            }
            if ($comment_info && $comment_info['article_id'] !== (int) $data['article_id']) {
                $this->error = '文章信息有误';
                return false;
            }
        }
        $article_info = model('article/Article')
                        ->where('id','=',$data['article_id'])
                        ->where('current_id','=',$data['current_id'])
                        ->where('status','=',1)
                        ->find();
        if (!$article_info) {
            $this->error = '评论文章信息未找到';
            return false;
        }
        Db::startTrans();
        try {
            $result = $this->model->create($data);
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        Db::commit();
        return $result;
    }

    /**
     * 软删除
     * @param int $id 评论id
     * @return mixed
     */
    public function destroy($id = 0, $current_id = '') {
        if (empty($id)) {
            $this->error = '要删除的评论信息不能为空';
            return false;
        }
        $info = $this->model
                ->where('id','=',$id)
                ->where('current_id','=',$current_id)
                ->find();
        if (!$info) {
            $this->error = '评论信息未找到';
            return false;
        }
        Db::startTrans();
        try {
            $info->destroy($id);
            $children_ids = $this->get_children_ids($id);
            if ($children_ids) {
                $this->model->destroy($children_ids);
            }
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            Db::rollback();
            return false;
        }
        Db::commit();
        return $info;
    }

    /**
     * 递归获取所有下级得id
     * @param  int  $id  记录id
     * @return $data
     */
    public function get_children_ids($id, $data = []){
        $child_ids = $this->model->where('pid','=',$id)->column('id');
        if($child_ids){
            $data = array_merge($data, $child_ids);
            foreach ($child_ids as $_current_id) {
                $data = $this->get_children_ids($_current_id, $data);
            }
        }
        return $data;
    }

    /**
     * 递归获取所有下级评论
     * @param  int  $id  记录id
     * @return $data
     */
    public function get_children($id, $maps = [], $data = []){
        $children = $this->model->where('pid','=',$id)->where($maps)->relation(['parent_info'])->select();
        if(!empty($children)){
            $data = array_merge($data, $children->toArray());
            foreach ($children as $key => $value) {
                $data = $this->get_children($value['id'], $maps, $data);
            }
        }
        return $data;
    }

}